import axios from '../utils/axios.js'
import qs from 'qs'
import { setCookie } from '../utils/index.js'
/**
 * 创建批量任务
 * @param {Object} params - 请求所需的参数对象，通常包括但不限于：
 *   - type: {String} 任务类型标识符 （例如："SHARE_SAVE"）
 *   - taskInfos: {Array} 需要处理的文件列表
 *   - targetFolderId: {String} 保存目录ID
 *   - shareId: {Object} 分享ID
 * @param {Object} cookies - 包含用户会话信息的cookies对象
 * @returns {Promise} - 返回axios库发起的POST请求的Promise对象
 */
const createBatchTask = (params, cookies) => {
  const url = `https://cloud.189.cn/api/open/batch/createBatchTask.action?noCache${Math.random()}`
  try {
    return axios.post(url, qs.stringify(params), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        accept: 'application/json;charset=UTF-8',
        'sign-type': '1',
        'Browser-Id': 'f8947534d7a9fd164b23469f8341bc71',
        cookie: setCookie(cookies),
        origin: 'https://cloud.189.cn',
      },
    })
  } catch (error) {
    console.error('Error occurred:')
  }
}
/**
 * 校验任务状态
 * @param {Object} params - 请求所需的参数对象，通常包括但不限于：
 *   - type: {String} 任务类型标识符 （例如："SHARE_SAVE"）
 *   - taskId: {String｜Number} 任务ID
 * @param {Object} cookies - 包含用户会话信息的cookies对象
 * @returns {Promise} - 返回axios库发起的POST请求的Promise对象
 */
const checkBatchTask = (params, cookies) => {
  const url = `https://cloud.189.cn/api/open/batch/checkBatchTask.action?noCache=${Math.random()}`
  try {
    return axios.post(url, qs.stringify(params), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        accept: 'application/json;charset=UTF-8',
        'sign-type': '1',
        'Browser-Id': '0a7189968638bf30042cd837e65b617f',
        cookie: setCookie(cookies),
      },
    })
  } catch (error) {
    console.error('Error occurred:', error)
  }
}
// 执行检查任务状态函数
const checkBatchTaskFn = (params, count = 0) => {
  count++
  if (count > 10) {
    return
  }
  const { taskId, type, cookies, result } = params

  checkBatchTask(
    {
      taskId,
      type,
    },
    cookies,
  ).then((res) => {
    if (res.data.res_code == 0 && res.data.taskStatus == 4) {
      result.status(200).json(res.data)
      return
    }
    if (res.data.res_code == 0 && res.data.taskStatus == -1) {
      // 结束循环
      result.status(500).json(res.data)
      return
    }
    if (res.data.res_code == 0 && res.data.taskStatus != 4 && res.data.taskStatus != -1) {
      // 进入循环
      setTimeout(() => {
        checkBatchTaskFn(params, count)
      }, 1500)
    }
  })
}

export default {
  createBatchTask,
  checkBatchTask,
  checkBatchTaskFn,
}
